package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.model.SocialUser;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.MobilePhoneExistException;
import com.atguigu.gulimall.member.exception.UserNameExistException;
import com.atguigu.gulimall.member.vo.MemberRegistryVo;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public void registry(MemberRegistryVo memberRegistryVo) throws UserNameExistException, MobilePhoneExistException {
        MemberEntity memberEntity = new MemberEntity();
        //默认设置
        MemberLevelEntity defaultMemberLevelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(defaultMemberLevelEntity.getId());
        //检查用户名和手机号是否唯一 为了让上层感知，使用异常机制
        this.checkUserNameUnique(memberRegistryVo.getUserName());
        this.checkMobileUnique(memberRegistryVo.getPhone());
        //设置
        memberEntity.setUsername(memberRegistryVo.getUserName());
        memberEntity.setMobile(memberRegistryVo.getPhone());
        //密码要加密存储
        /**
         * MD5
         *
         * 压缩性：任意长度的数据，算出的MD5值都是固定的
         * 容易计算：从原数据计算到MD5很容易
         * 抗修改性：原数据进行任何改动，得到的MD5都有很大区别
         * 强碰撞性：很难找到两个原数据得到相同的MD5
         * 不可逆
         *
         * 因为彩虹表 123456 -> e10adc3949ba59abbe56e057f20f883e
         * MD5不能直接进行密码的加密存储                                                                             DigestUtils.md5Hex(password)
         *
         * 盐值加密：常用密码经MD5加密后可通过彩虹表反向破解，密码MD5后加随机值($1$+8位随机字符)再次加密防彩虹表                  Md5Crypt.md5Crypt(password.getBytes());
         * 存储盐值，知道盐值和密码，可得固定密文
         *
         * Spring的BCryptPasswordEncoder，将盐存储到密文中，无需另外存储盐值
         */
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        memberEntity.setPassword(passwordEncoder.encode(memberRegistryVo.getPassword()));
        this.baseMapper.insert(memberEntity);
    }

    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {
        String loginAccount = memberLoginVo.getLoginAccount();
        String password = memberLoginVo.getPassword();
        MemberEntity memberEntity = this.getBaseMapper().selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAccount).or().eq("mobile", loginAccount));
        if (memberEntity == null) {
            return null;
        } else {
            String passwordDB = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, passwordDB);
            if (matches) {
                return memberEntity;
            }
        }
        return null;
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        //登录和注册合并逻辑
        String uid = socialUser.getUid();
        MemberEntity socialMemberEntity = this.getBaseMapper().selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (socialMemberEntity == null) {
            //账号不存在,进行注册
            socialMemberEntity = new MemberEntity();
            HashMap<String, String> query = new HashMap<>();
            query.put("access_token", socialUser.getAccess_token());
            query.put("uid", socialUser.getUid());
            //查询社交账号基本信息
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), query);
            if (response.getStatusLine().getStatusCode() == 200) {
                //查询成功
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String name = jsonObject.getString("name");
                String gender = jsonObject.getString("gender");
                //....
                socialMemberEntity.setUsername(name);
                socialMemberEntity.setGender("m".equals(gender) ? 1 : 0);
                //...
                socialMemberEntity.setSocialUid(Long.parseLong(uid));
                socialMemberEntity.setAccessToken(socialUser.getAccess_token());
                socialMemberEntity.setExpiresIn(socialUser.getExpires_in());
                this.getBaseMapper().insert(socialMemberEntity);
            }
        } else {
            socialMemberEntity.setSocialUid(Long.parseLong(uid));
            socialMemberEntity.setAccessToken(socialUser.getAccess_token());
            socialMemberEntity.setExpiresIn(socialUser.getExpires_in());
            this.getBaseMapper().updateById(socialMemberEntity);
        }
        return socialMemberEntity;
    }

    private void checkUserNameUnique(String userName) throws UserNameExistException {
        MemberEntity memberEntity = this.getBaseMapper().selectOne(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (memberEntity != null)
            throw new UserNameExistException();
    }

    private void checkMobileUnique(String phone) throws MobilePhoneExistException {
        MemberEntity memberEntity = this.getBaseMapper().selectOne(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (memberEntity != null)
            throw new MobilePhoneExistException();
    }


}